package com.example.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.common.Result;
import com.example.entity.Repair;
import com.example.entity.RepairStatsDto;
import com.example.entity.StatsDto;
import com.example.entity.WorkerDto;
import com.example.service.AdminRepairService;
import com.example.service.UserRepairService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 账单表前端操作接口
 **/
@RestController
@RequestMapping("/admin/repair")
public class AdminRepairController {

    @Resource
    private AdminRepairService adminRepairService;
    @Resource
    private UserRepairService userRepairService;

    /**
     * 新增
     */
    @PostMapping("/add")
    public Result add(@RequestBody Repair repair) {
        adminRepairService.add(repair);
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        adminRepairService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     */
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        adminRepairService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public Result updateById(@RequestBody Repair repair) {
        adminRepairService.updateById(repair);
        return Result.success();
    }

    /**
     * 评价
     */
    @PostMapping("/evaluate")
    public Result evaluateById(@RequestBody Repair repair) {
        // TODO 添加评价前提判断
        adminRepairService.updateById(repair);
        return Result.success();
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Repair bill = adminRepairService.selectById(id);
        return Result.success(bill);
    }

    /**
     * 查询所有
     */
    @GetMapping("/selectAll")
    public Result selectAll(Repair repair) {
        List<Repair> list = adminRepairService.selectAll(repair);
        return Result.success(list);
    }

    /**
     * 分页查询
     */
    @GetMapping("/selectPage")
    public Result selectPage(Repair repair,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Repair> page = adminRepairService.selectPage(repair, pageNum, pageSize);
        return Result.success(page);
    }

    /**
     *  分配
     */
    @PostMapping("/assign")
    public Result assignRepair(@RequestBody WorkerDto workerDto) {
        Repair repair = new Repair();
        repair.setId(workerDto.getId());
        repair.setWorker1Id(workerDto.getWorkerId().get(0));
        repair.setWorker2Id(workerDto.getWorkerId().get(1));
        repair.setRepairPerson1(workerDto.getWorkerName().get(0));
        repair.setRepairPerson2(workerDto.getWorkerName().get(1));
        repair.setRepairPerson1Phone(workerDto.getWorkerPhone().get(0));
        repair.setRepairPerson2Phone(workerDto.getWorkerPhone().get(1));
        repair.setRepairStatus("处理中");
        adminRepairService.updateById(repair);
        List<String> toUser = workerDto.getWorkerUserName();
        userRepairService.notice(toUser, "您有新的维修单需要处理-处理中");
        return Result.success();
    }

    @GetMapping("/export")
    public void export(@RequestParam(required = false) String repairType,
                       @RequestParam(required = false) String repairStatus,
                       HttpServletResponse response) throws IOException {
        List<Repair> repairList;
        Repair repair = new Repair();
        if(repairType != null) {
            repair.setRepairType(repairType);
        }
        if(repairStatus != null) {
            repair.setRepairStatus(repairStatus);
        }
        repairList = adminRepairService.selectAll(repair);
        ExcelWriter excelWriter = ExcelUtil.getWriter();
        excelWriter.addHeaderAlias("id", "序号");
        excelWriter.addHeaderAlias("repairNumber", "报修单号"); // 修改此处
        excelWriter.addHeaderAlias("buildingNumber", "楼号"); // 修改此处
        excelWriter.addHeaderAlias("repairAddress", "报修地址"); // 修改此处
        excelWriter.addHeaderAlias("reporter", "报修人");
        excelWriter.addHeaderAlias("contactPhone", "联系电话"); // 修改此处
        excelWriter.addHeaderAlias("repairContent", "报修内容"); // 修改此处
        excelWriter.addHeaderAlias("repairType", "维修类型");
        excelWriter.addHeaderAlias("repairStatus", "维修状态");
        excelWriter.addHeaderAlias("repairPerson1", "维修人1"); // 修改此处以保持一致性（虽然原字段名已经是驼峰）
        excelWriter.addHeaderAlias("repairPerson1Phone", "维修人1电话"); // 添加Phone为驼峰命名
        excelWriter.addHeaderAlias("repairPerson2", "维修人2"); // 同样保持一致性
        excelWriter.addHeaderAlias("repairPerson2Phone", "维修人2电话"); // 添加Phone为驼峰命名
        excelWriter.addHeaderAlias("rating", "评分");
        excelWriter.addHeaderAlias("comments", "评价内容");
        excelWriter.addHeaderAlias("reportTime", "报修时间"); // 修改此处
        excelWriter.setOnlyAlias(true);  // 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        excelWriter.write(repairList);

        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("报修单数据", "UTF-8") + ".xls");
        try(ServletOutputStream os = response.getOutputStream()){
            excelWriter.flush(os, true);
        }finally{
            excelWriter.close();
        }
    }
    @GetMapping("/statsExport")
    public void export(HttpServletResponse response) throws IOException {
        Repair repair = new Repair();
        StatsDto statsDto = adminRepairService.statuses(repair);
        List<StatsDto> statsList = new ArrayList<>();
        statsList.add(statsDto);
        ExcelWriter excelWriter = ExcelUtil.getWriter();
        excelWriter.addHeaderAlias("totalRepairs", "维修总数");
        excelWriter.addHeaderAlias("successRate", "维修完成率"); // 修改此处
        excelWriter.addHeaderAlias("averageRating", "平均评分"); // 修改此处

        excelWriter.setOnlyAlias(true);  // 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        excelWriter.write(statsList);

        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("统计报表", "UTF-8") + ".xls");
        try(ServletOutputStream os = response.getOutputStream()){
            excelWriter.flush(os, true);
        }finally{
            excelWriter.close();
        }
    }

    // 统计账单的比例情况
    @GetMapping("/count")
    public Result count(String type) {
        List<Repair> list = adminRepairService.count(type);
        return Result.success(list);
    }

    @GetMapping("/statuses")
    public Result statuses(Repair repair) {
        StatsDto statsDto = adminRepairService.statuses(repair);
        return Result.success(statsDto);
    }
    @GetMapping("/statusPie")
    public Result statusPie(Repair repair) {
        List<RepairStatsDto> statsDto = adminRepairService.statusPie(repair);
        return Result.success(statsDto);
    }
    @GetMapping("/ratingDistribution")
    public Result ratingDistribution(Repair repair) {
        List<Integer> statsDto = adminRepairService.ratingDistribution(repair);
        return Result.success(statsDto);
    }

}